import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/class/ClassDetails.dart';
import 'package:ichinesereader/pages/common/report/studentReportBottom.dart';
import 'package:ichinesereader/routes/routePages.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/widgets/grids/studentsReportDataGrid.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:ichinesereader/widgets/sidebars/adminReportSidebar.dart';
import 'package:sidebarx/sidebarx.dart';
import '../../themes/appTheme.dart';

class SchoolAdminReportsStudent extends StatefulWidget {
  SchoolAdminReportsStudent({Key? key}) : super(key: key);
  static const String routeName = '/schooladmin/reports/student';

  @override
  _SchoolAdminReportsStudent createState() => _SchoolAdminReportsStudent();
}

class _SchoolAdminReportsStudent extends State<SchoolAdminReportsStudent> {
  final ReportsController _reportsController = Get.find();
  final SchoolAdminController _schoolAdminController = Get.find();
  var box = Hive.box('appconfig');

  bool isSchoolAdmin = false;
  var selectedClass;
  var selectedTime = Constants.timeRanges[0];
  var startTime;
  var endTime;

  @override
  void initState() {
    isSchoolAdmin = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_SchoolAdmin;

    if (isSchoolAdmin) {
      if (_schoolAdminController.classItemsWithoutAll.isEmpty) {
        _schoolAdminController.fetchSchoolAllClassesDetailsWithoutAll();
      }
      Future.delayed(Duration(milliseconds: 800), () {
        if (_schoolAdminController.classItemsWithoutAll.isNotEmpty) {
          var temp = _schoolAdminController.classItemsWithoutAll[0];
          fetchOverallData(temp, startTime, endTime);
          setState(() {
            selectedClass = temp;
          });
        }
      });
    }
    super.initState();
  }

  void fetchOverallData(ClassDetails sClass, startTime, endTime) {
    if (sClass.classId != null) {
      var classId = sClass.classId;
      _reportsController.fetchClassOverviewDetails(
          classId!, startTime, endTime);
    }
  }

  @override
  Widget build(BuildContext context) {
    // final isSmallScreen =
    //     MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;
    int _selectedSidebarItem = RoutePages.schoolAdminPageItems
        .indexWhere((page) => page.route == Get.currentRoute);
    final SidebarXController _xController = SidebarXController(
        selectedIndex: _selectedSidebarItem, extended: isBigScreen);
    final PageStyles _pageStyles = PageStyles();

    Log.debug('build SchoolAdminReportsStudent');
    return Container(
      decoration: _pageStyles.pageBoxDecoration(),
      child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: CustomAppBar(title: 'Student Reports'.tr),
          body: Container(
              child: Row(children: [
            Visibility(
                visible: false,
                child: AdminReportSidebarX(controller: _xController)),
            Expanded(
                child: isSchoolAdmin
                    ? Center(
                        child: Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: Column(
                            children: [
                              Row(children: [
                                DropdownButton(
                                  dropdownColor: Get.isDarkMode
                                      ? AppTheme.colors.darkTheme3
                                      : Get.theme.primaryColorLight,
                                  icon: Icon(
                                    Icons.arrow_drop_down_outlined,
                                    color: Colors.white54,
                                  ),
                                  hint: Text(
                                    'Choose Class'.tr,
                                    style: TextStyle(
                                        color: Get.isDarkMode
                                            ? Get.theme.primaryColorDark
                                            : Colors.black),
                                  ),
                                  value: selectedClass,
                                  items: _schoolAdminController
                                      .classItemsWithoutAll
                                      .map((selectedClass) {
                                    return DropdownMenuItem(
                                      value: selectedClass,
                                      child: Text(
                                        selectedClass.className.toString(),
                                        style: Theme.of(context)
                                            .textTheme
                                            .titleLarge
                                            ?.copyWith(
                                                color: Get.isDarkMode
                                                    ? Get.theme.primaryColorDark
                                                    : Colors.black),
                                        overflow: TextOverflow.fade,
                                      ),
                                    );
                                  }).toList(),
                                  onChanged: (value) {
                                    value as ClassDetails;
                                    setState(() {
                                      selectedClass = value;
                                    });
                                    fetchOverallData(value, startTime, endTime);
                                  },
                                ),
                                Expanded(
                                  child: StudentReportBottom(
                                    classId: selectedClass != null
                                        ? selectedClass.classId
                                        : "",
                                    selectedTime: selectedTime,
                                    updateSelectedTime: (arg) {
                                      setState(() {
                                        selectedTime = arg;
                                      });
                                    },
                                    startTime: startTime,
                                    endTime: endTime,
                                    updateCustomTime: (arg1, arg2) {
                                      setState(() {
                                        startTime = arg1;
                                        endTime = arg2;
                                      });
                                      fetchOverallData(
                                          selectedClass, arg1, arg2);
                                    },
                                  ),
                                ),
                              ]),
                              Expanded(
                                  flex: 9,
                                  child: _reportsController.obx((data) {
                                    if (_reportsController
                                                .classoverviewdetailsresult
                                                .value
                                                .result !=
                                            null &&
                                        selectedClass != null &&
                                        selectedClass.classId != null &&
                                        _reportsController
                                                .classoverviewdetailsresult
                                                .value
                                                .result!
                                                .dataList !=
                                            null &&
                                        _reportsController
                                            .classoverviewdetailsresult
                                            .value
                                            .result!
                                            .dataList!
                                            .isNotEmpty) {
                                      return StudentsReportDataGrid(
                                          studentOverviewItems:
                                              _reportsController
                                                  .classoverviewdetailsresult
                                                  .value
                                                  .result!
                                                  .dataList!,
                                          classId: selectedClass.classId);
                                    } else {
                                      return StudentsReportDataGrid(
                                          studentOverviewItems: [],
                                          classId: selectedClass.classId);
                                    }
                                  }))
                            ],
                          ),
                        ),
                      )
                    : Text(''))
          ]))),
    );
  }
}
